//
//  StatusViewModel.swift
//  Weibo
//
//  Created by 李亚乐 on 15/12/11.
//  Copyright © 2015年 李亚乐. All rights reserved.
//

import UIKit

// MARK: - 微博视图模型
class StatusViewModel: CustomStringConvertible {
    
    /// 微博数据模型
    var status: Status
    /// 缩略图 URL 数组 - 存储性属性
    var thumbnailURLs: [NSURL]?
    /// 用户默认头像
    var userDefaultIcon = UIImage(named: "avatar_default_big")
    
    // MARK: - 计算性属性
    /// 懒加载 计算行高
    lazy var rowHeight: CGFloat = {
        var cell: StatusCell
        
        if self.status.retweeted_status == nil {
            cell = StatusNormalCell(style: .Default, reuseIdentifier: WBStatusCellNormalId)
        }else {
            cell = StatusRetweetedCell(style: .Default, reuseIdentifier: WBStatusCellRetweetedId)
        }
        
        return cell.calculateRowHeight(self)
    }()
    
    /// 用户头像 URL
    var userIconViewURL: NSURL {
        let urlString = status.user?.profile_image_url
        return NSURL(string: urlString ?? "")!
    }
    
    /// 成员等级
    var userMemberIcon: UIImage? {
        if status.user?.mbrank > 0 && status.user?.mbrank < 7 {
            return UIImage(named: "common_icon_membership_level\(status.user?.mbrank)")
        }
        return nil
    }
    
    // 认证类型，-1：没有认证，0，vip，2,3,5: 企业认证，220: 达人
    /// 用户 vip 认证
    var userVipIcon: UIImage? {
        switch (status.user?.verified_type ?? -1) {
        case 0: return UIImage(named: "avatar_vip")
        case 2, 3, 5: return UIImage(named: "avatar_enterprise_vip")
        case 220: return UIImage(named: "avatar_grassroot")
        default: return nil
        }
    }
    
    /// 转发微博文字内容
    var retweetedText: String? {
        guard let retweet = status.retweeted_status else {
            return nil
        }
        return "@" + (retweet.user?.screen_name ?? "") + ":"  + (retweet.text ?? "")
    }
    
    /// cell 的可重用 ID
    var cellID: String {
        return status.retweeted_status == nil ? WBStatusCellNormalId : WBStatusCellRetweetedId
    }
    
    /// 构造方法
    ///
    /// - parameter status: 微博模型
    /// - returns: 视图模型
    init(status: Status) {
        
        self.status = status
        
        if let urls = status.retweeted_status?.pic_urls ?? status.pic_urls {
            thumbnailURLs = [NSURL]()
            
            for dict in urls {
                let url = NSURL(string: dict["thumbnail_pic"]!)
                thumbnailURLs?.append(url!)
            }
        }
    }
    
    var description: String {
        return status.description //+ "配图数组 \(thumbnailURLs ?? [] as NSArray)"
    }

}